/**
 * @author mashaodong
 * @class 对腾讯IM做一层封装
 */
import tim from "./imConfig/index";
import TIM from "tim-js-sdk";
import { upLoadFile } from "./utils/uploadFile";
import { timCallbackFuns } from "./callback";
import { Message } from "element-ui";

export default class ImTim {
  constructor() {
    this.tim = tim;
    timCallbackFuns.call(this);
  }
  timLogin({ userId, config }) {
    this.tim
      .login({
        userID: userId,
        userSig: config.userSig,
      })
      .then(() => {
        setTimeout(() => {
          if (this.timGroupID) {
            this.timJoinGroup(this.timGroupID);
          } else {
            this.timCreateGroup(userId);
          }
        }, 3000);
      })
      .catch((error) => {
        Message({
          type: "error",
          message: "IM登录失败：" + error.message,
        });
      });
  }
  // 创建聊天群
  async timCreateGroup(userId) {
    const params = {
      avatar: "",
      introduction: "",
      name: "临时会议",
      type: TIM.TYPES.GRP_MEETING,
      groupID: this.roomId,
      memberList: [],
    };
    const res = await this.tim.createGroup(params);
    if (res.code === 0) {
      const groupID = res.data.group.groupID;
      this.timGroupID = groupID;
      this.getTimGroupID(groupID);
    }
  }
  // 加入群
  async timJoinGroup(groupID) {
    let imResponse = await this.tim.joinGroup({
      groupID: groupID,
      type: TIM.TYPES.GRP_MEETING,
    });
    switch (imResponse.data.status) {
      case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL:
        break; // 等待管理员同意
      case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
        console.log("加群成功"); // 加入的群组资料
        break;
      case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
        break;
      default:
        break;
    }
  }
  // 退出群
  async timQuitGroup(groupID) {
    const res = await this.tim.quitGroup(groupID);
    if (res.code === 0) {
      console.log(res.data.groupID); // 退出成功的群 ID
    }
  }
  // 创建消息实例，接口返回的实例可以上屏
  async timCreateTextMessage({ type, content }) {
    const message = this.tim.createTextMessage({
      to: this.timGroupID,
      conversationType: TIM.TYPES.CONV_GROUP,
      payload: {
        text: JSON.stringify({ type, content }),
      },
    });
    const res = await this.timSendMessage(message);
    return res;
  }
  // 发送消息
  async timSendMessage(message) {
    await this.tim.sendMessage(message);
    return { status: true };
  }
  async timUpLoadFile(sendFile, getFileUrl) {
    upLoadFile(sendFile, getFileUrl);
  }
  // 获取加入的群组列表
  timGetGroupList() {
    let promise = tim.getGroupList();
    promise
      .then(function(imResponse) {
        console.log(imResponse.data.groupList); // 群组列表
      })
      .catch(function(imError) {
        console.warn("getGroupList error:", imError); // 获取群组列表失败的相关信息
      });
  }
}
